import { Card } from "@/components/Card";
import { OrderState, PayType } from "@/constants/enums/goods";
import { deliverGoodsOrder, getGoodsOrderDetail, getLogisticsData } from "@/services/goods";
import { useRequest } from "ahooks";
import { Button, Input, Modal, Select, Spin, Steps, Table, message } from "antd";
import dayjs from "dayjs";
import { useEffect, useMemo, useState } from "react";
import { Access } from '@umijs/max'

const statusMap = (state?: OrderState) => {
  switch (state) {
    case OrderState.待支付: return '等待买家付款'
    case OrderState.支付成功: return '等待卖家发货'
    case OrderState.发货: return '等待买家收货'
    case OrderState.收货: return '买家已收货'
    case OrderState.取消: return '订单已取消'
    case OrderState.售后中: return '售后中，等待卖家处理'
    case OrderState.退款: return '卖家已退款'
    default: return ''
  }
}
const statusTipMap = (state?: OrderState, countdown?: string) => {
  switch (state) {
    case OrderState.待支付: return `如买家未在${countdown}内付款，订单将自动取消。`
    case OrderState.支付成功: return '买家已付款，请尽快发货，否则买家有权申请退款。'
    case OrderState.发货: return '订单已发货，请等待买家确认收货'
    case OrderState.收货: return '买家已确认收货，订单已完成'
    case OrderState.取消: return '超时未付款。'
    case OrderState.售后中: return '买家申请售后，等待处理'
    case OrderState.退款: return '已退款'
    default: return ''
  }
}
const getStepCurrent = (state?: OrderState) => {
  switch (state) {
    case OrderState.待支付: return 0
    case OrderState.支付成功: return 1
    case OrderState.发货: return 2
    case OrderState.收货: return 3
    case OrderState.取消: return 3
    case OrderState.售后中: return 3
    case OrderState.退款: return 3
    default: return 3
  }
}
const payTypeMap = (type?: PayType) => {
  switch (type) {
    case PayType.余额: return '余额支付'
    case PayType.微信支付: return '微信支付'
    default: return '--'
  }
}
let interval: any
const format = (val: number) => {
  if (val < 0) return ''
  const _minute = String(Math.floor(val / 60)).padStart(2, '0')
  const _second = String(val % 60).padStart(2, '0')
  return `${_minute}:${_second}`
} 
const expressCompanyList = [
  {label: '跨越速运', value: 'KYEXPRESS'},
  {label: '顺丰', value: 'SFEXPRESS'},
  {label: '中通', value: 'ZTO'},
  {label: '壹米滴答', value: 'YIMIDIDA'},
]

const GoodsOrderDetail: React.FC<RoutePageProps> = props => {
  const { data, loading, runAsync, refresh } = useRequest(getGoodsOrderDetail, {manual: true})
  const deliverReq = useRequest(deliverGoodsOrder, {manual: true})
  const logisticsData = useRequest(getLogisticsData, {manual: true})
  const [countdown, setCountdown] = useState(0)
  const [countDownText, setCountDownText] = useState('')

  const setCountDown = (createTime: string) => {
    let countDown = dayjs(createTime).add(15, 'minute').diff(dayjs(), 'second') + 2
    setCountdown(countDown)
    if (countDown < 1) {
      refresh()
    } else {
      setCountDownText(format(countDown))
      interval = setInterval(() => {
        setCountdown(old => {
          const _new = old - 1
          setCountDownText(format(_new))
          if (_new < 1) {
            refresh()
            clearInterval(interval!)
            interval = null
          }
          return _new
        })
      }, 1000)
    }
  }

  const detail: Goods.Order | undefined = useMemo(() => {
    if (data?.data) {
      if (data.data.orderState === OrderState.待支付) {
        setCountDown(data.data.createTime)
      }
      
      return {
        ...data.data,
        _payInfo: JSON.parse(data.data.payInfo!),
        _deduction: JSON.parse(data.data.deduction),
        content: data.data.content.map(it => {
          const _contentInfo = JSON.parse(it.contentInfo)
          _contentInfo._goodsShow = JSON.parse(_contentInfo.goodsShow)
          return {...it, _contentInfo}
        })
      }
    }
    return undefined
  }, [data?.data])
  const deliverGoods = () => {
    let companyCode = ''
    let logistics = ''
    Modal.confirm({
      title: '快递单号',
      content: <div>
        <Select placeholder='快递公司' style={{width: '100%', marginBottom:16}} options={expressCompanyList} onChange={value => companyCode = value} />
        <Input placeholder="快递单号" onChange={({target}) => logistics = target.value} />
      </div>,
      onOk: async () => {
        logistics = logistics.trim()
        if (!companyCode) {
          message.error('请选择快递公司')
          return Promise.reject()
        }
        if (!logistics) {
          message.error('请输入有效的快递单号')
          return Promise.reject()
        }
        return deliverReq.runAsync({
          orderId: detail!.orderId,
          companyCode,
          logistics,
        }).then(refresh)
      }
    })
  }

  useEffect(() => {
    if (props.params.id) {
      runAsync({orderId: props.params.id}).then(res => {
        if (res.data.logistics) {
          let logisticsId = res.data.logistics
          if (logisticsId?.startsWith('SF')) { // 顺丰快递，需要拼接手机号后4位
            logisticsId = `${logisticsId}:${String(res.data.phone).substring(7)}`
          }
          logisticsData.runAsync({orderId: props.params.id, logistics: res.data.logistics}).then((_res: any) => {
            if (_res.data) {
              const _data = JSON.parse(_res.data)
              console.log(_data)
              if (_data.status === '0') {
                logisticsData.mutate(_data.result)
              } else {
                logisticsData.mutate(undefined)
              }
            }
          })
        }
      })
    }

    return () => {
      if (interval) {
        clearInterval(interval)
        interval = null
      }
    }
  }, [props.params])

  return <Spin spinning={loading}>
    <Card header={<div className="flex gap-2">
      <div>订单号：{detail?.orderCode}</div>
      <div>下单时间：{detail ? dayjs(detail.createTime).format('YYYY-MM-DD HH:mm:ss') : ''}</div>
    </div>}>
      {/* 状态，流程 */}
      <div className="flex">
        <div className="grow">
          <div className="text-lg font-semibold">{statusMap(detail?.orderState)}</div>
          <div className="text-gray-400 mt-2">{statusTipMap(detail?.orderState, countDownText)}</div>
          <Access accessible={detail?.orderState === OrderState.支付成功}>
            <div className="mt-3">
              <Button type="primary" onClick={deliverGoods}>发货</Button>
            </div>
          </Access>
        </div>
        <div className="shrink-0 w-[800px]" style={{display: detail?.orderState === OrderState.取消 ? 'none' : 'block'}}>
          <Steps
            current={getStepCurrent(detail?.orderState)}
            labelPlacement="vertical"
            items={[
              {title: '买家下单', description: detail?.createTime ? dayjs(detail.createTime).format('YYYY-MM-DD HH:mm:ss') : ''},
              {title: '买家付款', description: detail?.payTime ? dayjs(detail.payTime).format('YYYY-MM-DD HH:mm:ss') : ''},
              {title: '商家发货', description: detail?.deliverTime ? dayjs(detail.deliverTime).format('YYYY-MM-DD HH:mm:ss') : ''},
              {title: '交易成功', description: detail?.takeTime ? dayjs(detail.takeTime).format('YYYY-MM-DD HH:mm:ss') : ''},
            ]}
          />
        </div>
      </div>
      {/* 物流信息 */}
      <Access accessible={!!logisticsData.data}>
        <div className="flex mt-6" style={{overflowX: 'auto', gap: 8}}>
          <div className="w-0 grow flex flex-col gap-2 flex-shrink" style={{minWidth: 180}}>
            <div className="font-medium">物流信息</div>
            <div className="text-gray-400">发货方式：快递</div>
            <div>
              <span className="text-gray-400">快递公司：</span>
              <span>{logisticsData.data?.expName || '-- (暂无物流信息)'}</span>
            </div>
            <div>
              <span className="text-gray-400">快递单号：</span>
              <span>{detail?.logistics?.split(':')[0]}</span>
            </div>
          </div>
          {
            logisticsData.data?.list?.map((item: any, index: number) => {
              return <div key={index} className="w-0 grow flex flex-col gap-2 flex-shrink" style={{minWidth: 180}}>
                <div className="text-gray-400">{item.time.split(' ')[0].substring(5)}</div>
                <div className="text-gray-400">{item.time.split(' ')[1]}</div>
                <div className="text-gray-400">{item.status}</div>
              </div>
            })
          }
        </div>
      </Access>
      {/* 订单明细 */}
      <div className="flex mt-6">
        <div className="w-0 grow flex flex-col gap-2">
          <div className="font-medium">收货人信息</div>
          <div>
            <span className="text-gray-400">收货人：</span>
            <span>{detail?.recipient}</span>
          </div>
          <div>
            <span className="text-gray-400">联系电话：</span>
            <span>{detail?.phone}</span>
          </div>
          <div>
            <span className="text-gray-400">收货地址：</span>
            <span>{detail?.address}</span>
          </div>
        </div>
        <Access accessible={!!detail?.payInfo}>
          <div className="w-0 grow flex flex-col gap-2">
            <div className="font-medium">付款信息</div>
            <div>
              <span className="text-gray-400">买家：</span>
              <span>{detail?.nickName || '--'}</span>
            </div>
            <div>
              <span className="text-gray-400">实付金额：</span>
              <span>{detail?._payInfo?.amount}</span>
            </div>
            <div>
              <span className="text-gray-400">付款方式：</span>
              <span>{payTypeMap(detail?.payType)}</span>
            </div>
            <div>
              <span className="text-gray-400">付款时间：</span>
              <span>{detail?.payTime ? dayjs(detail.payTime).format('YYYY-MM-DD HH:mm:ss') : '--'}</span>
            </div>
          </div>
        </Access>
      </div>
      {/* 商品信息 */}
      <div className="mt-6">
        <Table<Goods.OrderContent>
          rowKey={'contentId'}
          dataSource={detail?.content}
          pagination={false}
          columns={[
            {title: '商品', key: 'contentInfo', render: (_, record) => {
              return <div className={`w-80 flex`}>
                <img className="w-12 h-12 mr-2 shrink-0" src={record._contentInfo._goodsShow[0].source} />
                <div className="grow">
                  <div>{record._contentInfo.goodsName}</div>
                  <div>{record._contentInfo.stockName}</div>
                </div>
              </div>
            }},
            {title: '单价/数量', key: 'singlePrice', render: (_, record) => {
              record._contentReceivable = JSON.parse(record.contentReceivable)
              const _price = record._contentReceivable.find(it => it.type === 'Cost')
              return <div>
                <div>¥ {_price.amount}</div>
                <div>{record.num} 件</div>
              </div>
            }},
            {title: '小计(元)', key: 'total', render: (_, record) => {
              record._contentReceivable = JSON.parse(record.contentReceivable)
              const _price = record._contentReceivable.find(it => it.type === 'Cost')
              return (_price.amount * record.num).toFixed(2)
            }}
          ]}
          footer={() => {
            const _deduction: Goods.Order['_deduction'] = JSON.parse(detail?.deduction || '[]')
            const _price = _deduction.reduce((init, item) => {
              if (item.type === 'Cost') {
                init.goods += item.num
              } else if (item.type === 'Coupon') {
                init.coupon += item.num
              } else if (item.type === 'Logistics') {
                init.logistics += item.num
              }
              return init
            }, {goods: 0, coupon: 0, logistics: 0})
            const _payInfo = detail?.payInfo ? JSON.parse(detail?.payInfo) : undefined
            return <div>
              <div className="flex justify-end">
                <div className="w-24">商品总价：</div>
                <div className="w-24">¥{_price.goods.toFixed(2)}</div>
              </div>
              <div className="flex justify-end">
                <div className="w-24">快递费用：</div>
                <div className="w-24">¥{_price.logistics.toFixed(2)}</div>
              </div>
              <Access accessible={!!_price.coupon}>
                <div className="flex justify-end">
                  <div className="w-24">优惠减免：</div>
                  <div className="w-24">-¥{_price.coupon.toFixed(2)}</div>
                </div>
              </Access>
              <div className="mt-3 flex justify-end">
                <div className="w-24 font-medium">{_payInfo ? '实收金额：' : '应收金额：'}</div>
                <div className="w-24 font-medium" style={{color: '#ff4040'}}>¥{_payInfo ? _payInfo.amount : detail?.amount || '0.00'}</div>
              </div>
            </div>
          }}
        />
      </div>
    </Card>
  </Spin>
}

export default GoodsOrderDetail
